package net.forty2ware.vintagesofa

import org.apache.commons.lang.builder.EqualsBuilder
import org.apache.commons.lang.builder.HashCodeBuilder

/**
 * This class represents a CouchDB server.
 */
class Server {

  private CouchDbHelper couchDbHelper = new CouchDbHelper()

  String hostname
  int port
  String context = ''

  void setContext(String context) {
    if (!context) {
      context = ''
    }
    this.context = (context ==~ /^$|^\/.+$/) ? context : '/' + context
  }

  def getDatabases() {
    def databases = []

    def list = couchDbHelper.listDatabases(this)
    list.each{ name ->
      databases.add(new Database('server':this, 'name':name))
    }

    return databases
  }

  @Override
  public boolean equals(Object o) {
    if (o == null) { return false; }
    if (o == this) { return true; }
    if (obj.getClass() != getClass()) {
      return false;
    }

    Server rhs = (Server)o;
    return new EqualsBuilder()
      .append(hostname, rhs.hostname)
      .append(port, rhs.port)
      .append(context, rhs.context)
      .isEquals()
  } 

  @Override
  public int hashCode() {
    return new HashCodeBuilder(11, 187)
      .append(hostname)
      .append(port)
      .append(context)
      .toHashCode()
  }

}
